package com.xydtech.ecard.ecard.controller;

import com.xydtech.common.config.XydtechBusiPlatConfig;
import com.xydtech.common.enums.ResultStatus;
import com.xydtech.common.model.ResponseModel;
import com.xydtech.common.utils.GeoUtil;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.common.utils.file.FileUploadUtils;
import com.xydtech.common.utils.file.MimeTypeUtils;
import com.xydtech.ecard.config.domain.EcardDeptPackageOrg;
import com.xydtech.ecard.config.service.IEcardDeptPackageOrgService;
import com.xydtech.ecard.dept.domain.EcardApiSysDept;
import com.xydtech.ecard.dept.service.IEcardApiSysDeptService;
import com.xydtech.ecard.ecard.service.EcardApiPunchInService;
import com.xydtech.ecard.statistics.domain.EcardUserChecking;
import com.xydtech.ecard.user.domain.EcardApiUserInfo;
import com.xydtech.ecard.user.service.IEcardApiUserService;
import com.xydtech.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 电子名片打卡接口类
 *
 * @author yjs
 * @date 2022/7/29 11:28
 */

@Controller
@Api(tags = "电子名片-打卡相关接口")
@RequestMapping("/ecardSaasApi/punchIn")
public class EcardApiPunchInController extends EcardApiBaseController {
    protected final Logger logger = LoggerFactory.getLogger(EcardApiPunchInController.class);
    @Autowired
    private EcardApiPunchInService ecardApiPunchInService;
    @Autowired
    private IEcardApiUserService ecardApiUserService;
    @Autowired
    private IEcardApiSysDeptService eardApiSysDeptService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IEcardDeptPackageOrgService ecardDeptPackageOrgService;

    /**
     * 获取本周打卡统计
     *
     * @author yjs
     * @date 2022/7/28 10:48
     */
    @GetMapping(value = "/getWeekPunchInCount")
    @ApiOperation(value = "电子名片-本周打卡统计", notes = "电子名片-本周打卡统计")
    @ApiImplicitParam(name = "checkingType", value = "打卡类型，1-营销打卡，2-包保打卡", dataType = "String", dataTypeClass = String.class, paramType = "query", required = true)
    @ResponseBody
    public ResponseModel getWeekPunchInCount(@RequestParam(required = false) String checkingType) {
        try {
            String salt = getSalt();//盐值
            if (StringUtils.isEmpty(checkingType)) {
                return ResponseModel.error(ResultStatus.PARAMETER_ERROR);
            }
            //获取当前登录人ID
            String currentUserId = getCurrentUserId();
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);

            if ("1".equals(checkingType)) {//	营销打卡
                List<EcardUserChecking> punchInRecordList = ecardApiPunchInService.getNotFixedWeekPunchInList(userInfo.getUserId());
                return ResponseModel.ok(punchInRecordList.size());
            } else {//包保打卡
                List<Map<String, Object>> list = ecardApiPunchInService.getFixedWeekPunchInCount(userInfo.getUserId());
                if (list != null && list.size() > 0) {
                    return ResponseModel.ok(list);
                } else {
                    return ResponseModel.ok(0);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("查询打卡数据失败");
        }
    }

    /**
     * 查询不同打卡类型打卡记录
     *
     * @author yjs
     * @date 2022/7/28 10:48
     */
    @GetMapping(value = "/getPunchInList")
    @ApiOperation(value = "电子名片-获取打卡记录", notes = "电子名片-获取打卡记录")
    @ApiImplicitParam(name = "checkingType", value = "打卡类型，1-营销打卡，2-包保打卡", dataType = "String", dataTypeClass = String.class, paramType = "query", required = true)
    @ResponseBody
    public ResponseModel getPunchInList(@RequestParam(required = false) String checkingType) {
        try {
            String salt = getSalt();//盐值
            if (StringUtils.isEmpty(checkingType)) {
                return ResponseModel.error(ResultStatus.PARAMETER_ERROR);
            }
            //获取当前登录人ID
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            EcardUserChecking userChecking = new EcardUserChecking();
            userChecking.setUserId(userInfo.getUserId());
            userChecking.setDeptId(userInfo.getDeptId());
            userChecking.setCheckingType(checkingType);
            userChecking.setLimit(5);
            List<EcardUserChecking> userCheckingList = ecardApiPunchInService.getPunchInRecordList(userChecking);
            return ResponseModel.ok(userCheckingList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("获取打卡记录失败");
        }
    }

    /**
     * 查询机构下包保（固定）打卡点
     *
     * @author yjs
     * @date 2022/7/28 10:48
     */
    @GetMapping(value = "/getFixedPunchPoint")
    @ApiOperation(value = "电子名片-查询机构下包保（固定）打卡点", notes = "电子名片-查询机构下包保（固定）打卡点")
    @ResponseBody
    public ResponseModel getFixedPunchPoint() {
        try {
            String salt = getSalt();//盐值
            //获取当前登录人ID
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            EcardDeptPackageOrg dept = new EcardDeptPackageOrg();
            dept.setDeptId(userInfo.getDeptId());
            List<EcardDeptPackageOrg> deptPackageOrgList = ecardApiPunchInService.getFixedPunchPoint(dept);
            return ResponseModel.ok(deptPackageOrgList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("获取打卡点失败");
        }
    }

    /**
     * 包保（定点）打卡验证打卡人和打卡地的距离
     *
     * @author yjs
     * @date 2022/7/28 10:48
     */
    @GetMapping(value = "/checkClockInRange")
    @ApiOperation(value = "电子名片-验证打卡人和机构之间的距离", notes = "电子名片-验证打卡人和机构之间的距离")
    @ApiImplicitParam(name = "coordinate", value = "所在位置", dataType = "String", dataTypeClass = String.class, paramType = "query", required = true)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "coordinate", value = "所在位置", dataType = "String", dataTypeClass = String.class, paramType = "query", required = true),
            @ApiImplicitParam(name = "orgId", value = "打开机构ID", dataType = "Long", dataTypeClass = String.class, paramType = "query", required = true)
    })
    @ResponseBody
    public ResponseModel checkClockInRange(@RequestParam(required = false) String coordinate, @RequestParam(required = false) Long orgId) {
        try {
            String salt = getSalt();//盐值
            if (StringUtils.isEmpty(coordinate) && StringUtils.isEmpty(orgId.toString())) {
                return ResponseModel.error(ResultStatus.PARAMETER_ERROR);
            }
            logger.info("打卡地经纬度=========" + coordinate);
            //获取当前登录人信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            //验证是否已存在打卡记录
            EcardUserChecking userChecking = new EcardUserChecking();
            userChecking.setUserId(userInfo.getUserId());
            userChecking.setOrgId(orgId);
            userChecking.setCheckingType("2");
            userChecking.setCreateTime(new Date());
            List<EcardUserChecking> inRecordList = ecardApiPunchInService.getPunchInRecordList(userChecking);
            if (inRecordList != null && inRecordList.size() > 0) {
                return ResponseModel.error("今日已打卡！");
            }
            EcardApiSysDept depInfo = eardApiSysDeptService.getDepInfo(orgId, salt);
            EcardDeptPackageOrg ecardDeptPackageOrg = new EcardDeptPackageOrg();
            ecardDeptPackageOrg.setDeptId(userInfo.getDeptId());
            ecardDeptPackageOrg.setOrgId(orgId);
            List<EcardDeptPackageOrg> deptPackageOrg = ecardDeptPackageOrgService.selectEcardDeptPackageOrgList(ecardDeptPackageOrg);
            //距离范围值
            Integer range = deptPackageOrg.get(0).getScopeLimit() == null ? 0 : deptPackageOrg.get(0).getScopeLimit();
            logger.info("距离范围值=========" + range);
            //客户与支行之间的距离值
            Double distance = 0.00;
            //腾讯地图请求地址
            //String tencentMapUrl = configService.selectConfigByKey(ApiContant.TECENT_MAP_URL);
            //腾讯地图请求Key
            // String tencentMapKey = configService.selectConfigByKey(ApiContant.TECENT_MAP_KEY);
            RestTemplate restTemplate = new RestTemplate();
            String orgCoordinate = depInfo.getCoordinate();
            logger.info("打卡机构经纬度=========" + orgCoordinate);
            if (orgCoordinate != null && StringUtils.isNotEmpty(orgCoordinate)) {
               /* String url = tencentMapUrl + "?mode=straight&from=" + coordinate + "&to=" + orgCoordinate + "&key=" + tencentMapKey;
                logger.info("请求腾讯地图Url=========" + url);
                TencentMapDistance tencentMapDistance = restTemplate.getForObject(url, TencentMapDistance.class);
                if (tencentMapDistance.getStatus() == 0) {
                    distance = tencentMapDistance.getResult().getRows().get(0).getElements().get(0).getDistance();
                }*/
                //打卡地经纬度
                String clockInPlace[] = coordinate.split(",");
                //打卡机构经纬度
                String orgPlace[] = orgCoordinate.split(",");
                distance = GeoUtil.GetDistance(Double.valueOf(clockInPlace[1]), Double.valueOf(clockInPlace[0]), Double.valueOf(orgPlace[1]), Double.valueOf(orgPlace[0]));
            }
            logger.info("计算结果（米）=========" + distance);
            if (distance > range) {
                return ResponseModel.error("不在打卡范围内！");
            } else {
                return ResponseModel.ok();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("校验打卡位置失败，请联系管理员");
        }
    }

    /**
     * 添加打卡数据
     *
     * @author yjs
     * @date 2022/7/28 10:48
     */
    @PostMapping(value = "/addPunchPoint")
    @ApiOperation(value = "电子名片-添加打卡记录", notes = "电子名片-添加打卡记录")
    @ResponseBody
    public ResponseModel addPunchPoint(EcardUserChecking ecardUserChecking, @RequestParam("imageFile") MultipartFile imageFile) {
        try {
            String salt = getSalt();//盐值
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            //当前打卡人userId
            ecardUserChecking.setUserId(userInfo.getUserId());
            //打卡人机构ID
            ecardUserChecking.setDeptId(userInfo.getDeptId());

            if (!imageFile.isEmpty()) {

                //20230711 add 加入文件类型后缀判断
                FileUploadUtils.uploadCheckType(imageFile, MimeTypeUtils.IMAGE_EXTENSION);

                String imgUrl = XydtechBusiPlatConfig.getEcardFilePath() + "/" + userInfo.getDeptId() + "/punchInImage/" + imageFile.getOriginalFilename();
                logger.info("文件路径========" + imgUrl);
                File file = new File(imgUrl);
                if (!file.getParentFile().exists()) {
                    //创建上级目录
                    file.getParentFile().mkdirs();
                }
                //图片添加水印后保存
                addWaterMask(imageFile, imgUrl, ecardUserChecking.getLocation(), ecardUserChecking.getCoordinate(), userInfo.getUserName(), userInfo.getDeptName());
                ecardUserChecking.setImgUrl(imgUrl.replaceAll(XydtechBusiPlatConfig.getProfile(), "/profile"));
                int updateCount = ecardApiPunchInService.addPunchPoint(ecardUserChecking);
                return updateCount > 0 ? ResponseModel.ok() : ResponseModel.error("打开失败！");
            } else {
                return ResponseModel.error("打卡照片不能为空！");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("打卡失败");
        }
    }
}
